clear
set scheme s2mono
version 18.5

// Required packages:
// coefplot
// grc1leg
// esttab

global replocation "Your-location-here"

global outputfolder "${replocation}\Output"
 
cd "$replocation/Data"

use Sautmann-Brown-Dean_Mali-Timing-of-Care_ReStat.dta, clear


// ! Decide on failure definition: 1 only formal doctor, 2 CSCOM, 3 all formal (incl. pharmacy), 4 informal 
global faildate "faildate1"
global fail "fail1"

 
// create covariate macros
global ChildCov "Gender_Imp "
global FACov "LitFA LangFA GenderFA SalaryFA OldFA HHmembers_12 OOccupier "

// dummy out missing vars
foreach var in $ChildCov $FACov dist1 LogAssets {
gen `var'dummy=1
replace `var'dummy=0 if `var'<.
replace `var'=0 if `var'dummy==1
}

// note: LitFAdummy=LangFAdummy=SalaryFAdummy, LogAssetsdummy=OOccupierdummy
global Dummies "Gender_Impdummy LitFAdummy GenderFAdummy OldFAdummy HHmembers_12dummy OOccupierdummy dist1dummy "

cap log close

log using "$outputfolder/Summary_Stats_Tables", replace text

log off

*******************************************************************
// Table 1: TREATMENT EFFECTS ON COST


// Aggregate by child:

eststo clear 

foreach var in ChildVisits_F ChildVisits_C ChildVisits_P ChildVisits_O ChildCost ChildCostC ChildCostP ChildCostO ChildWait ChildValue ChildValueC {
// sample mean
	 reg `var'   if FCo+HWo+HWFC==0 , vce(cluster compound)
	local temp : di %-4.3f _b[_cons]
	xi: reg `var'  FC HW HWFC i.Stratum $FACov $ChildCov dist1 LogAssets $Dummies if child_tag==1  ,  vce(cluster compound)
	estadd local samplemean "`temp'"
	eststo 
}


esttab, b(3) se(3)  star(* .1 ** .05 *** .01)  keep (FC HW HWFC)


   #delimit ;
		esttab using "$outputfolder/Table1",  
			b(3) se(3)  star(* .1 ** .05 *** .01)  
			 replace label  noobs  nonotes 
			 stats( samplemean N , labels("Control group mean" "N" ) fmt(%9.2f  %10s ))   
			keep(FC HW HWFC)
			order(FC HW HWFC )
			coef( FC "Received subsidy"
				HW "Received CHW visits" 
				HWFC "Subsidy x CHW")
	;
	#delimit cr	

	
	eststo clear

**********************************************************
// Table 2 :spell and consultation numbers by treatment group and whether spell enters care required

// Create variables first
// spell_tag==1 denotes end of spell -- fail1=1 is care received

//  Req on last day: care ever required spell
gen spell_req= Req==1 if spell_tag==1
label variable spell_req "Care ever required spell"
//  ReqN on last day: care never required spell
gen spell_nreq= ReqN==1 if spell_tag==1
label variable spell_nreq "Care never required spell"

// consultation took place
gen care= fail1 ==1 if spell_tag==1
label variable care "Consultation"

// consultation took place X spell type

gen screq_cons=   care*spell_req
label variable screq_cons "Care ever required, consultation"
gen scnreq_cons = care*spell_nreq
label variable scnreq_cons "Care never required, consultation"

qui log on
**********************************************************
// TABLE 2

// ** Columns **: Control, CHW only, Subsidy only, Full program, Total

// ***** Panel 1: consultations

// Share care required

 forvalues i=1/4 {
 	display(" *** Treatment arm `i' ***")
	display("1 Control, 2 CHW, 3 Subsidy, 4 Full program")
	mean  screq_cons if care==1 & TrtOrder==`i',  vce(cluster compound)
  }
 mean  screq_cons if care==1 ,  vce(cluster compound)
 
 // Number of observations (consultations)
 tabstat  care , by(TrtOrder) statistic(sum) 
 
 
 // ***** Panel 2: Spells: share with care required and consultation
 
 // By treatment arm (column): report share of spells with Care never required, Care never required & consultation, Care ever required, Care ever required & consultation
 
  forvalues i=1/4 {
  	 	display(" *** Treatment arm `i' ***")
	display("1 Control, 2 CHW, 3 Subsidy, 4 Full program")
	mean  spell_nreq scnreq_cons spell_req screq_cons if TrtOrder==`i',  vce(cluster compound)
  }
// Last column: full sample 

 mean  spell_nreq scnreq_cons spell_req screq_cons ,  vce(cluster compound)

 // Number of observations (spells)
estpost tabstat   spell_tag , by(TrtOrder) statistic(sum)
 
 // ***** Panel 3: Spells conditional on care never required: share ending in consultation
 
// By treatment arm (column)
  forvalues i=1/4 {
  	 	display(" *** Treatment arm `i' ***")
	display("1 Control, 2 CHW, 3 Subsidy, 4 Full program")
	mean  care if spell_nreq &  TrtOrder==`i',  vce(cluster compound)
  }
 // full sample
	mean  care if spell_nreq ,  vce(cluster compound)
	
 // Number of observations (spells care never required)
 tabstat  spell_nreq , by(TrtOrder) statistic(sum) 
	
// **** Panel 4: spells conditional on care ever required: share ending in consultation

// By treatment arm (column)
 forvalues i=1/4 {
 	 	display(" *** Treatment arm `i' ***")
	display("1 Control, 2 CHW, 3 Subsidy, 4 Full program")
		mean  care if spell_req &  TrtOrder==`i',  vce(cluster compound)
  }
// full sample
	mean  care if spell_req ,  vce(cluster compound) 
	
 // Number of observations (spells care ever required)
 tabstat  spell_nreq , by(TrtOrder) statistic(sum)  
qui log off

 
**********************************************************
// Table 3: Treatment effects, Cox proportional hazard model

// full sample 

eststo clear

// setting up the calendar for hazard estimation using spell level variables

// spellID: unique identifier for spells
egen spellID=group(IDvar spellno)
// within spellID, find number of last day with same "care required" status
bysort spellID Req : egen end_crq=max(spdayno) if spellset1==1

// generate "spell" descriptors, consisting of length of subspell with same care-required status
gen relevant=1 if spdayno==end_crq & spellset1==1
drop end_crq
stset spdayno if relevant==1, id(spellID) failure(fail1 ==1) 
drop  relevant

	
// Cox regression coefficients

* simple treatment dummies
	stcox FC HW  HWFC $ChildCov LogAssets  dist1  $FACov $Dummies , vce(cluster compound) strata(Stratum) nohr
	  eststo 
	  
* interactions
 	stcox Req FC ReqFC  HW ReqHW HWFC ReqHWFC  $ChildCov LogAssets  dist1  $FACov $Dummies , vce(cluster compound) strata(Stratum) nohr
 	  eststo 
	

// create top panel of the table
   #delimit ;
		esttab using "$outputfolder/Table3",  
			b(3) se(3)  star(* .1 ** .05 *** .01)  
			replace label  noobs  nonotes 			
			order( Req FC ReqFC HW ReqHW HWFC ReqHWFC) 
			keep( Req FC ReqFC HW ReqHW HWFC ReqHWFC)
			coef( Req "Care required" FC "Received subsidy" ReqFC "Subsidy x Care  req." HW "Received CHW visits" ReqHW "CHW x Care req." HWFC "Subsidy x CHW" ReqHWFC "Subs. x CHW x Care req.")
			fragment
			;
	#delimit cr	

eststo clear

// get hazard ratios relative to reference group and reference group mean

* simple treatment dummies
	// control group mean:
	sum fail1 if spellset==1 & FCo+HWo+HWFC==0
	local temp1=r(mean)
	
	// Cox regression 
	stcox FCo HWo  HWFC $ChildCov LogAssets  dist1  $FACov $Dummies , vce(cluster compound) strata(Stratum) 
	 estadd  local refgroup "Control group"
	 estadd scalar refmean= `temp1'
	eststo 
	
* interactions	
	// control group mean:
	sum fail1 if spellset==1 & FCo+HWo+HWFC+Req==0
	local temp1=r(mean)
 	stcox ReqControl ReqNFCo ReqFCo  ReqNHWo ReqHWo ReqNHWFC ReqHWFC  $ChildCov LogAssets  dist1  $FACov $Dummies , vce(cluster compound) strata(Stratum) 
	// compare subsidy+required effect in the required group with subsidy effect in early group
		estadd  local refgroup "Control, care not req. days"
		estadd scalar refmean= `temp1'
 	eststo 
	
// add Panel B
  #delimit ;
		esttab using "$outputfolder/Table3", eform 
			b(3)   nostar  
			 label  noobs  nonotes 			
			order( ReqControl FCo ReqNFCo ReqFCo HWo ReqNHWo ReqHWo HWFC ReqNHWFC ReqHWFC) 
			keep(  FCo  HWo  HWFC ReqControl ReqNFCo ReqFCo  ReqNHWo ReqHWo ReqNHWFC ReqHWFC)
			coef( ReqControl "Control, care required" 
			FCo "Subsidy only group"
			ReqNFCo "Subsidy only, care not req." 
			ReqFCo "Subsidy only, care req." 
			HWo "CHW visits only group"
			ReqNHWo "CHW visits only, care not req." 
			ReqHWo "CHW visits only, care req." 
			HWFC "Full program group"
			ReqNHWFC "Full program, care not req." ReqHWFC "Full program, care req.")
			append
			stats(  N_sub refgroup refmean , 
			 labels( "N" "Reference group" "Ref. group mean daily prob. of care")
			 fmt(  %10s   %10s %9.3f  ))
			;
	#delimit cr	
		
eststo clear


******************************************************************
// Figure 2: Probability of care seeking by day, by care required


// REGRESSION 1: all "not required" are just named `var'A`i', required are named L 

// generate all variable interactions
	foreach var1 in Control HWo FCo HWFC  {
	forvalues i=1/7 {
   qui gen `var1'A`i'=(`var1' ==1 & spdayno==`i')*(1-Req) if spellset1 ==1 
     label var `var1'A`i' "`i'"
      qui gen `var1'L`i'=(`var1' ==1 & spdayno==`i')*(Req) if spellset1==1
     label var `var1'L`i' "`i'"

   }
 
   qui gen `var1'Ag7 =(`var1' ==1 & spdayno>7)*(1-Req) if spellset1==1 
     label var `var1'Ag7 ">7"
   qui gen `var1'Lg7 =(`var1' ==1 & spdayno>7)*(Req) if spellset1==1 
     label var `var1'Lg7 ">7"

  }
 
reg fail1  ControlA* ControlL* HWoA* HWoL* FCoA* FCoL* HWFCA* HWFCL*  if spellset1==1 , vce(cluster compound) nocons
 eststo Early
 
 // REGRESSION 2: all "required" are now named `var'A`i' to combine in coefplot.
 
// generate all variable interactions
 foreach var1 in Control HWo FCo HWFC  {
	forvalues i=1/7 {
		rename `var1'A`i' `var1'E`i'
		label var `var1'E`i' "`i'"
		rename `var1'L`i' `var1'A`i'
		label var `var1'A`i' "`i'"
	}
   rename `var1'Ag7 `var1'Eg7 
   label var `var1'Eg7 ">7"
   rename `var1'Lg7 `var1'Ag7
   label var `var1'Ag7 ">7"
  }
  
  reg fail1 ControlE* ControlA* HWoE* HWoA* FCoE* FCoA* HWFCE* HWFCA*  if spellset1==1 , vce(cluster compound) nocons
 eststo Late

 coefplot (Early, keep(ControlA* ) label(early)  ) (Late, keep(ControlA*  ) label(care required))  ///
  ,  vertical yline(0) yscale(range(0 .2)) ylabel(0.05 0.1 0.15 0.2) graphregion(color(white))  title("Control") format(%9.2f) recast(line) lcolor(gs12)  addplot(scatter @b @at, ms(o) mcolor(gs4) mlabel(@b)  mlabposition(11) mlabgap(*2) mlabangle(315)  mlabcolor(black))
    graph save ${outputfolder}/NP-Control.gph , replace
 
  coefplot (Early, keep(FCoA* ) label(early)) (Late, keep(FCoA*  ) label(care required))  ///
  , vertical yline(0) yscale(range(0 .2)) ylabel(0.05 0.1 0.15 0.2) graphregion(color(white)) ///
  title("Subsidy only") format(%9.2f) recast(line) lcolor(gs12)  addplot(scatter @b @at, ms(o) mcolor(gs4) mlabel(@b)  mlabposition(11) mlabgap(*2) mlabangle(315)  mlabcolor(black))
      graph save ${outputfolder}/NP-Subsidy.gph , replace
	  
  
   coefplot (Early, keep(HWoA* ) label(early)) (Late, keep(HWoA*  ) label(care required))  ///
  , vertical yline(0) yscale(range(0 .2)) ylabel(0.05 0.1 0.15 0.2) graphregion(color(white)) ///
  title("CHW only") format(%9.2f) recast(line) lcolor(gs12)  addplot(scatter @b @at, ms(o) mcolor(gs4) mlabel(@b)  mlabposition(10) mlabgap(*2) mlabangle(315)  mlabcolor(black))
      graph save ${outputfolder}/NP-CHWonly.gph , replace
  
   coefplot (Early, keep(HWFCA* ) label(early)) (Late, keep(HWFCA*  ) label(care required))  ///
  , vertical yline(0) yscale(range(0 0.2)) ylabel(0.05 0.1 0.15 0.2) graphregion(color(white)) ///
  title("Subsidy & CHW") format(%9.2f) recast(line) lcolor(gs12)  addplot(scatter @b @at, ms(o) mcolor(gs4) mlabel(@b)  mlabposition(10) mlabgap(*2) mlabangle(315)  mlabcolor(black))
      graph save ${outputfolder}/NP-full.gph , replace
  
  
   grc1leg  "$outputfolder/NP-Control.gph" "$outputfolder/NP-Subsidy.gph" "$outputfolder/NP-CHWonly.gph" "$outputfolder/NP-full.gph" , ycommon graphregion(color(white)) name(Fig2, replace) saving("$outputfolder/Figure2.gph", replace)




preserve

use Sautmann-Brown-Dean_Mali-Timing-of-Care_Attrition_ReStat.dta, clear
 
qui log on

************************************************************************
// ATTRITION Table B.1

// Note: main health calendar only contains observations present at 2013 endline.
// Data used below is an extract of the census.


// ** Columns **: Control, CHW only, Subsidy only, Full program, Total

// From census to baseline - Panel 1
 tab AttrStatusBL TrtOrder
// From baseline to endline, original sample - Panel 2
 tab AttrStatus TrtOrder if AttrStatus>=1 & AttrStatus<=6
 // proportion retained baseline to endline: 
 gen Retained=AttrStatus==6 if AttrStatus>=1 & AttrStatus<=6
 tab TrtOrder, summarize(Retained)
 //added observations baseline to endline - Panel 3
 tab AttrStatus TrtOrder if inlist(AttrStatus,6,7)
 
 qui log off
restore
	

*************************************************************************
// DEMOGRAPHICS AND BALANCE Table B.2

preserve

keep FPrimary Person_ID  $ChildCov $AgeCov $FACov LogAssets dist1 FCo HWo HWFC KeyChild2012 KeyChild2013 CO HH ID compound Stratum

 duplicates drop  

 // child level variables:
  
 foreach var in $ChildCov {
  	// sample mean
	 reg `var'   if FCo+HWo+HWFC==0 , vce(cluster compound)
	local temp : di %-4.3f _b[_cons]
	 xi:reg `var' FCo HWo HWFC i.Stratum , vce(cluster compound)
	estadd local samplemean "`temp'"
	eststo
	}
  
foreach var in $AgeCov {
  	// sample mean
	 reg `var'   if FCo+HWo+HWFC==0 , vce(cluster compound)
	local temp : di %-4.3f _b[_cons]
	 xi:reg `var' FCo HWo HWFC i.Stratum , vce(cluster compound)
	estadd local samplemean "`temp'"
	eststo
	}

qui drop $ChildCov $AgeCov Person_ID KeyChild2012 ID KeyChild2013 
qui duplicates drop

// family level variables:
 
foreach var in $FACov LogAssets   {
  	// sample mean
	 reg `var'   if FCo+HWo+HWFC==0 , vce(cluster compound)
	local temp : di %-4.3f _b[_cons]
	 xi:reg `var' FCo HWo HWFC i.Stratum , vce(cluster compound)
	estadd local samplemean "`temp'"
	eststo
}

// compound level - distance
keep compound FCo HWo HWFC dist1 Stratum
 duplicates drop 
 gen dist =exp(dist1) // reverse log of distance

  	// sample mean
	 reg dist if FCo+HWo+HWFC==0 , vce(cluster compound)
	local temp : di %-4.3f _b[_cons]
	 xi:reg dist FCo HWo HWFC i.Stratum , vce(cluster compound)
	estadd local samplemean "`temp'"
	eststo

   #delimit ;
		esttab using "$outputfolder/TableB2",  
			b(3) se(2)  star(* .1 ** .05 *** .01)  
			 replace label   nonotes  
			 stats( samplemean N , labels("Control group mean" "N" ) fmt(%9.2f  %10s ))  
			order(FCo HWo HWFC)
			keep(FCo HWo HWFC)
			coef( FCo "Subsidy only group"
				HWo "CHW only group" 
				HWFC "Full program group");
	#delimit cr	
	
	eststo clear
restore


qui log on
*************************************************************
// Table B.3: Summary stats visits

// Total cost

// // ** Columns **: Formal care, no subsidy - Formal care, subsidy - Private provider - Pharmacy - Informal care

//1 Total cost
eststo: estpost tabstat TotalCostVisitNFC TotalCostVisitFC  TotalCostVisitP TotalCostVisitO TotalCostVisitI ,  statistic(mean sem )


// 2 Value of care (formal care only)
estpost tabstat TotalValueVisitNFC TotalValueVisitFC  ,  statistic(mean sem )
// 3 average wait time
estpost tabstat WaitVisitNFC WaitVisitFC  WaitVisitP WaitVisitO WaitVisitI ,  statistic(mean sem )

//4 Share of visits with an antibiotic prescribed
	
estpost tabstat MedTypeAbNFC MedTypeAbFC MedTypeAbP MedTypeAbO MedTypeAbI,  statistic(mean sem )

// 5 Share of visits with an antimalarial prescribed
estpost tabstat MedTypeAmNFC MedTypeAmFC MedTypeAmP MedTypeAmO MedTypeAmI,  statistic(mean sem )

//6 number of visits, total

eststo: estpost tabstat Visits_NFC  Visits_FC  Visits_P Visits_O Visits_I ,  statistic(sum) columns(variables) 

// 7 number of visits, no subsidy
eststo: estpost tabstat Visits_NFC  Visits_FC  Visits_P Visits_O Visits_I if FC==0,  statistic(sum) columns(variables)

// 8 number of visits, subsidy
eststo: estpost tabstat Visits_NFC  Visits_FC  Visits_P Visits_O Visits_I if FC==1,  statistic(sum) columns(variables)

// 9 share care required by visit type:
// formal, no subsidy
sum Req if Visits_NFC>=1 & Visits_NFC!=.
// formal subsidy
sum Req if Visits_FC>=1 & Visits_FC!=.
// private
sum Req if Visits_P>=1 & Visits_P!=.
// pharmacy
sum Req if Visits_O>=1 & Visits_O!=.
// informal
sum Req if Visits_I>=1 & Visits_I!=.

qui log off

*************************************************************	
// Table B.4 ALL FORMAL CONSULTATIONS BY TREATMENT GROUP

// split visits during the spell into early and care required
foreach var in Acute FollowUp_inspell  {
gen `var'_Early = `var' if Req==0
gen `var'_Req   = `var' if Req==1
}

preserve

collapse  TrtOrder compound TrtRand HW FC HWFC (sum) Visits_C Visits_P Visits_I  Acute FollowUp_inspell FollowUp_outspell Other Acute_Early FollowUp_inspell_Early Acute_Req FollowUp_inspell_Req , by(FPrimary Person_ID)	

qui log on
*************************************************************	
// Table B.4: Formal consultations per child

// ** Columns "** : Acute visits (all, early, care required) -- In-spell follow-up visits (all, early, care required) -- Follow-up after spell -- Prevention/other

// 1 Control, 2 CHW 3 Subsidy 4 Full program
forvalues i=1/4 {
 	display(" *** Treatment arm `i' ***")
	display("1 Control, 2 CHW, 3 Subsidy, 4 Full program")
estpost tabstat   Acute Acute_Early Acute_Req FollowUp_inspell FollowUp_inspell_Early FollowUp_inspell_Req FollowUp_outspell Other  if TrtOrder==`i' , statistic(mean semean n)
}
qui log off

restore

 

******************************************************************************
// Table B.5 Symptoms in total and by need for care

estpost tabstat symptom1 symptom2 symptom3 symptom4 ///
				symptom5 symptom6 symptom8 symptom9 symptom10 symptom11 symptom12  symptom21 ///
				symptom23  symptom25 symptom20 symptom13  , statistics(mean sd) columns(statistics) 
	eststo
estpost tabstat symptom1 symptom2 symptom3 symptom4 ///
				symptom5 symptom6 symptom8 symptom9 symptom10 symptom11 symptom12  symptom21 ///
				symptom23  symptom25 symptom20 symptom13 if spellset1==1 , statistics(mean sd) columns(statistics) 
	eststo
estpost tabstat symptom1 symptom2 symptom3 symptom4 ///
				symptom5 symptom6 symptom8 symptom9 symptom10 symptom11 symptom12  symptom21 ///
				symptom23  symptom25 symptom20 symptom13 if Req==1 & spellset1==1 , statistics(mean sd) columns(statistics) 
	eststo
estpost tabstat symptom1 symptom2 symptom3 symptom4 ///
				symptom5 symptom6 symptom8 symptom9 symptom10 symptom11 symptom12  symptom21 ///
				symptom23  symptom25 symptom20 symptom13 if Req==0 & spellset1==1 , statistics(mean sd) columns(statistics) 
	eststo
				
esttab using "$outputfolder/TableB5", cells("mean (fmt(3)) sd (par fmt(2))") nostar collabels("Mean" "SD")  nonum  replace  label mtitle("All days" "Illness days" "Care required days" "Care not required days")

eststo clear

*************************************************************
// Table B.6 
// symptom and spell incidence by treatment group

// per child...
// Number of spells
// Number of days observed
// Share of illness days
// Share of symptom days for each symptom

// Number of spells per child:
destring spellno, gen(spellno2)
replace spellno2=. if spellsetCEN!=1
bysort FPrimary Person_ID: egen spells_child =max(spellno2)
replace spells_child =0 if spells_child ==. & child_tag==1


//Number of spells per child not left censored (used in Cox model):
destring spellno, gen(spellno3)
replace spellno3=. if spellset1 !=1
bysort FPrimary Person_ID: egen spells_Cox_child=max(spellno3) 
replace spells_Cox_child =0 if spells_Cox_child ==. & child_tag==1


// Number of observed days:
bysort FPrimary Person_ID: egen dayobs_child = total(dayobs)

// Generate average share of illness days and days with individual symptoms at the child level
foreach var in day symptom1 symptom2 symptom3 symptom4 symptom5 symptom6 symptom8 symptom9 symptom10 symptom11 symptom12  symptom21 symptom23  symptom25 symptom20 symptom13  {
		bysort FPrimary Person_ID: egen `var'_child = mean(`var')
				}	
label var spells_child "Spells (all)"
label var spells_Cox_child "Spells (not left-censored)"
label var dayobs_child "Total days observed"
label var day_child "Any symptom"
label var symptom1_child "Convulsions, spasms"
label var symptom2_child "Lethargic or unconscious"
label variable symptom3_child "Unable to drink"
label variable symptom4_child "Vomiting everything"
label var symptom5_child "Coughing"
label var symptom6_child "Difficulty breathing"
label var symptom8_child ">3 loose stools"
label variable symptom9_child "Blood in stool"
label variable symptom10_child "Sunken eyes"
label variable symptom11_child "Unusually hot"
label variable symptom12_child "Unusually cold"
label variable symptom21_child "Rash/spots/itch"
label variable symptom23_child "Head/neck/eye ache"
label variable symptom25_child "Cold symptoms"
label variable symptom20_child "Wound/injury/burn"
label variable symptom13_child "Other"

** Regressions:

foreach var in spells spells_Cox dayobs day symptom1 symptom2 symptom3 symptom4 symptom5 symptom6 symptom8 symptom9 symptom10 symptom11 symptom12  symptom21 symptom23  symptom25 symptom20 symptom13 {
	 reg `var'_child  if FCo+HWo+HWFC==0 & child_tag==1, vce(cluster compound)
	local temp : di %-4.3f _b[_cons]
	 xi:reg `var'_child FCo HWo HWFC i.Stratum $FACov $ChildCov dist1 LogAssets $Dummies if child_tag==1 , vce(cluster compound)
	estadd local samplemean "`temp'"
	eststo
}


#delimit ;
	esttab using "$outputfolder/TableB6", b(3) se(3)  star(* .1 ** .05 *** .01)  label  noobs  nonotes   stats( samplemean N , labels("Control group mean" "N" ) fmt(%9.2f  %10s))  order(FCo  HWo HWFC) keep(FCo  HWo  HWFC)coef( FCo "Subsidy only group" HWo "CHW only group " HWFC "Full program group") replace;
#delimit cr	
		
eststo clear
*/
*/


*************************************************************
// Table B7: Spell length by type of censoring


// define spell level variable of length by care required status
gen spdayno_Req = spdayno
replace spdayno_Req= . if Req!=1
gen spdayno_ReqN = spdayno
replace spdayno_ReqN= . if ReqN!=1

foreach var in spdayno spdayno_Req spdayno_ReqN {
// Cox spells
	gen `var'_temp1 = `var' if spell_tag==1
// All spells
	gen `var'_temp2 = `var' if spellCEN_tag==1 & spell_tag!=1
}

la var spdayno_temp1 "All spells" 
la var spdayno_Req_temp1 "Care required" 
la var spdayno_ReqN_temp1 "Care not required" 
la var spdayno_temp2 "All spells" 
la var spdayno_Req_temp2 "Care required"
la var spdayno_ReqN_temp2 "Care not required"

eststo clear

eststo: estpost tabstat  spdayno_temp1 spdayno_Req_temp1 spdayno_ReqN_temp1 , statistics(mean sd  p95 max N ) columns(statistics)

esttab using "$outputfolder/TableB7", ///
cells("mean (fmt(2)) sd (fmt(2)) p95(fmt(0)) max(fmt(0)) count(fmt(0))") noobs nonum nomtitles plain label replace fragment  type  collabels("Mean" "SD" "95th\%" "Max" "N")

eststo clear

eststo: estpost tabstat  spdayno_temp2 spdayno_Req_temp2 spdayno_ReqN_temp2 , statistics(mean sd  p95 max N ) columns(statistics) 

esttab using "$outputfolder/TableB7", cells("mean (fmt(2)) sd (fmt(2)) p95(fmt(0)) max(fmt(0)) count(fmt(0))") collabels(none)  noobs nonum nomtitles plain  label append

eststo clear


*************************************************************
// Table B.8 Cox model w pharmacies as formal care


// within spellID, find last day with same "care required" status
bysort spellID Req : egen end_crq=max(spdayno) if spellset3==1
// generate "spells" 
gen relevant=1 if spdayno==end_crq & spellset3==1
drop end_crq
stset spdayno if relevant==1, id(spellID) failure(fail3 ==1) 
drop  relevant

* simple treatment dummies
	stcox FC HW  HWFC $ChildCov LogAssets  dist1  $FACov $Dummies , vce(cluster compound) strata(Stratum) nohr
	  eststo 
	  
* interactions
 	stcox Req FC ReqFC  HW ReqHW HWFC ReqHWFC  $ChildCov LogAssets  dist1  $FACov $Dummies , vce(cluster compound) strata(Stratum) nohr
 	  eststo 
	

// create top panel of the table
   #delimit ;
		esttab using "$outputfolder/TableB8",  
			b(3) se(3)  star(* .1 ** .05 *** .01)  
			replace label  noobs  nonotes 			
			order( Req FC ReqFC HW ReqHW HWFC ReqHWFC) 
			keep( Req FC ReqFC HW ReqHW HWFC ReqHWFC)
			coef( Req "Care required" FC "Received subsidy" ReqFC "Subsidy x Care  req." HW "Received CHW visits" ReqHW "CHW x Care req." HWFC "Subsidy x CHW" ReqHWFC "Subs. x CHW x Care req.")
			fragment
			;
	#delimit cr	

eststo clear

// get hazard ratios relative to reference group and reference group mean

* simple treatment dummies
	// control group mean:
	sum fail3 if spellset==1 & FCo+HWo+HWFC==0
	local temp1=r(mean)
	
	// Cox regression 
	stcox FCo HWo  HWFC $ChildCov LogAssets  dist1  $FACov $Dummies , vce(cluster compound) strata(Stratum) 
	 estadd  local refgroup "Control group"
	 estadd scalar refmean= `temp1'
	eststo 
	
* interactions	
	// control group mean:
	sum fail3 if spellset==1 & FCo+HWo+HWFC+Req==0
	local temp1=r(mean)
 	stcox ReqControl ReqNFCo ReqFCo  ReqNHWo ReqHWo ReqNHWFC ReqHWFC  $ChildCov LogAssets  dist1  $FACov $Dummies , vce(cluster compound) strata(Stratum) 
	// compare subsidy+required effect in the required group with subsidy effect in early group
		estadd  local refgroup "Control, care not req. days"
		estadd scalar refmean= `temp1'
 	eststo 
	
// add Panel B
  #delimit ;
		esttab using "$outputfolder/TableB8", eform 
			b(3)   nostar  
			 label  noobs  nonotes 			
			order( ReqControl FCo ReqNFCo ReqFCo HWo ReqNHWo ReqHWo HWFC ReqNHWFC ReqHWFC) 
			keep(  FCo  HWo  HWFC ReqControl ReqNFCo ReqFCo  ReqNHWo ReqHWo ReqNHWFC ReqHWFC)
			coef( ReqControl "Control, care required" 
			FCo "Subsidy only group"
			ReqNFCo "Subsidy only, care not req." 
			ReqFCo "Subsidy only, care req." 
			HWo "CHW visits only group"
			ReqNHWo "CHW visits only, care not req." 
			ReqHWo "CHW visits only, care req." 
			HWFC "Full program group"
			ReqNHWFC "Full program, care not req." ReqHWFC "Full program, care req.")
			append
			stats(  N_sub refgroup refmean , 
			 labels( "N" "Reference group" "Ref. group mean daily prob. of care")
			 fmt(  %10s   %10s %9.3f  ))
			;
	#delimit cr	
		
eststo clear



*************************************************************
// Table B.9 Cox model incl. left censored spells

// within spellID, find last day with same "care required" status
bysort spellID Req : egen end_crq=max(spdayno) if spellsetCEN==1
// generate "spells" 
gen relevant=1 if spdayno==end_crq & spellsetCEN==1
drop end_crq
// full sample:
stset spdayno if relevant==1, id(spellID) failure(fail1 ==1) 
drop  relevant

* simple treatment dummies
	stcox FC HW  HWFC $ChildCov LogAssets  dist1  $FACov $Dummies , vce(cluster compound) strata(Stratum) nohr
	  eststo 
	  
* interactions
 	stcox Req FC ReqFC  HW ReqHW HWFC ReqHWFC  $ChildCov LogAssets  dist1  $FACov $Dummies , vce(cluster compound) strata(Stratum) nohr
 	  eststo 
	

// create top panel of the table
   #delimit ;
		esttab using "$outputfolder/TableB9",  
			b(3) se(3)  star(* .1 ** .05 *** .01)  
			replace label  noobs  nonotes 			
			order( Req FC ReqFC HW ReqHW HWFC ReqHWFC) 
			keep( Req FC ReqFC HW ReqHW HWFC ReqHWFC)
			coef( Req "Care required" FC "Received subsidy" ReqFC "Subsidy x Care  req." HW "Received CHW visits" ReqHW "CHW x Care req." HWFC "Subsidy x CHW" ReqHWFC "Subs. x CHW x Care req.")
			fragment
			;
	#delimit cr	

eststo clear

// get hazard ratios relative to reference group and reference group mean

* simple treatment dummies
	// control group mean:
	sum fail3 if spellset==1 & FCo+HWo+HWFC==0
	local temp1=r(mean)
	
	// Cox regression 
	stcox FCo HWo  HWFC $ChildCov LogAssets  dist1  $FACov $Dummies , vce(cluster compound) strata(Stratum) 
	 estadd  local refgroup "Control group"
	 estadd scalar refmean= `temp1'
	eststo 
	
* interactions	
	// control group mean:
	sum fail3 if spellset==1 & FCo+HWo+HWFC+Req==0
	local temp1=r(mean)
 	stcox ReqControl ReqNFCo ReqFCo  ReqNHWo ReqHWo ReqNHWFC ReqHWFC  $ChildCov LogAssets  dist1  $FACov $Dummies , vce(cluster compound) strata(Stratum) 
	// compare subsidy+required effect in the required group with subsidy effect in early group
		estadd  local refgroup "Control, care not req. days"
		estadd scalar refmean= `temp1'
 	eststo 
	
// add Panel B
  #delimit ;
		esttab using "$outputfolder/TableB9", eform 
			b(3)   nostar  
			 label  noobs  nonotes 			
			order( ReqControl FCo ReqNFCo ReqFCo HWo ReqNHWo ReqHWo HWFC ReqNHWFC ReqHWFC) 
			keep(  FCo  HWo  HWFC ReqControl ReqNFCo ReqFCo  ReqNHWo ReqHWo ReqNHWFC ReqHWFC)
			coef( ReqControl "Control, care required" 
			FCo "Subsidy only group"
			ReqNFCo "Subsidy only, care not req." 
			ReqFCo "Subsidy only, care req." 
			HWo "CHW visits only group"
			ReqNHWo "CHW visits only, care not req." 
			ReqHWo "CHW visits only, care req." 
			HWFC "Full program group"
			ReqNHWFC "Full program, care not req." ReqHWFC "Full program, care req.")
			append
			stats(  N_sub refgroup refmean , 
			 labels( "N" "Reference group" "Ref. group mean daily prob. of care")
			 fmt(  %10s   %10s %9.3f  ))
			;
	#delimit cr	
		
eststo clear

*************************************************************
// Figure B.1: Predicted survivor functions by treatment arm

global ndays 20

stcox if HW==0 & FC==0, vce(cluster compound) 
predict Scont, basesurv
qui bys Scont:  gen n = _n
gen nlnlScont = -log(-log(Scont))  if 1==n
drop n

stcox if HW==1 & FC==0, vce(cluster compound) 
predict Shw, basesurv
qui bys Shw:  gen n = _n
gen nlnlShw = -log(-log(Shw))  if 1==n
drop n

stcox if FC==1 & HW==0, vce(cluster compound) 
predict Sfc, basesurv
qui bys Sfc:  gen n = _n
gen nlnlSfc = -log(-log(Sfc))  if 1==n
drop n

stcox if HWFC==1      , vce(cluster compound) 
predict Shwfc, basesurv
qui bys Shwfc:  gen n = _n
gen nlnlShwfc = -log(-log(Shwfc))  if 1==n
drop n

graph twoway (line nlnlScont _t if _t<=$ndays+5, sort lw(thick) )   ///
	  (line nlnlShw   _t if _t<=$ndays, sort  lp(shortdash))   ///
     ( line nlnlSfc   _t if _t<=$ndays, sort lp(longdash) )  ///
	(  line nlnlShwfc _t if _t<=$ndays, sort lp(dot)	///
	xsc(log) xlab(1 2 5 10 20) ylab(0(1)4) xti("t (days)") yti("-log(-log(S(t)))") 	leg(label(1 "Control") label(2 "HW only") label(3 "FC only") label(4 "HW & FC")) name(FigB1, replace) graphregion(color(white)))
	
graph save "$outputfolder/FigureB1.gph", replace




*************************************************************
// Figure B.2: Probability of care seeking by day, by care required, w. pharmacies as formal care

// generate all variable interactions

// REGRESSION 1: all "not required" are just named `var'A`i', required are named L 
	foreach var1 in Control HWo FCo HWFC  {
	forvalues i=1/7 {
		drop `var1'A`i' `var1'E`i'
   qui gen `var1'A`i'=(`var1' ==1 & spdayno==`i')*(1-Req) if spellset3 ==1 
     label var `var1'A`i' "`i'"
      qui gen `var1'L`i'=(`var1' ==1 & spdayno==`i')*(Req) if spellset3==1
     label var `var1'L`i' "`i'"

   }
 drop  `var1'Ag7 `var1'Eg7
   qui gen `var1'Ag7 =(`var1' ==1 & spdayno>7)*(1-Req) if spellset3==1 
     label var `var1'Ag7 ">7"
   qui gen `var1'Lg7 =(`var1' ==1 & spdayno>7)*(Req) if spellset3==1 
     label var `var1'Lg7 ">7"

  }
 
reg fail1   ControlA* ControlL* HWoA* HWoL* FCoA* FCoL* HWFCA* HWFCL*  if spellset3==1 , vce(cluster compound) nocons
 eststo Early
 
 // REGRESSION 2: all "required" are now named `var'A`i' to combine in coefplot.

 	foreach var1 in Control HWo FCo HWFC  {
	forvalues i=1/7 {
  rename `var1'A`i' `var1'E`i'
     label var `var1'E`i' "`i'"
      rename `var1'L`i' `var1'A`i'
     label var `var1'A`i' "`i'"

   }
 
   rename `var1'Ag7 `var1'Eg7 
   label var `var1'Eg7 ">7"
   rename `var1'Lg7 `var1'Ag7
     label var `var1'Ag7 ">7"

  }
  
  reg fail1 ControlE* ControlA* HWoE* HWoA* FCoE* FCoA* HWFCE* HWFCA*  if spellset3==1 , vce(cluster compound) nocons
 eststo Late
 

coefplot (Early, keep(ControlA* ) label(early)  ) (Late, keep(ControlA*  ) label(care required))  ///
  ,  vertical yline(0) yscale(range(0 .2)) ylabel(0.05 0.1 0.15 0.2) graphregion(color(white))  title("Control") format(%9.2f) recast(line) lcolor(gs12)  addplot(scatter @b @at, ms(o) mcolor(gs4) mlabel(@b)  mlabposition(11) mlabgap(*2) mlabangle(315)  mlabcolor(black))
    graph save ${outputfolder}/NP-Control.gph , replace
 
  coefplot (Early, keep(FCoA* ) label(early)) (Late, keep(FCoA*  ) label(care required))  ///
  , vertical yline(0) yscale(range(0 .2)) ylabel(0.05 0.1 0.15 0.2) graphregion(color(white)) ///
  title("Subsidy only") format(%9.2f) recast(line) lcolor(gs12)  addplot(scatter @b @at, ms(o) mcolor(gs4) mlabel(@b)  mlabposition(11) mlabgap(*2) mlabangle(315)  mlabcolor(black))
      graph save ${outputfolder}/NP-Subsidy.gph , replace
	  
  
   coefplot (Early, keep(HWoA* ) label(early)) (Late, keep(HWoA*  ) label(care required))  ///
  , vertical yline(0) yscale(range(0 .2)) ylabel(0.05 0.1 0.15 0.2) graphregion(color(white)) ///
  title("CHW only") format(%9.2f) recast(line) lcolor(gs12)  addplot(scatter @b @at, ms(o) mcolor(gs4) mlabel(@b)  mlabposition(10) mlabgap(*2) mlabangle(315)  mlabcolor(black))
      graph save ${outputfolder}/NP-CHWonly.gph , replace
  
   coefplot (Early, keep(HWFCA* ) label(early)) (Late, keep(HWFCA*  ) label(care required))  ///
  , vertical yline(0) yscale(range(0 0.2)) ylabel(0.05 0.1 0.15 0.2) graphregion(color(white)) ///
  title("Subsidy & CHW") format(%9.2f) recast(line) lcolor(gs12)  addplot(scatter @b @at, ms(o) mcolor(gs4) mlabel(@b)  mlabposition(10) mlabgap(*2) mlabangle(315)  mlabcolor(black))
      graph save ${outputfolder}/NP-full.gph , replace
  
  
   grc1leg  "$outputfolder/NP-Control.gph" "$outputfolder/NP-Subsidy.gph" "$outputfolder/NP-CHWonly.gph" "$outputfolder/NP-full.gph" , ycommon graphregion(color(white)) name(FigB2, replace)
   graph save "$outputfolder/FigureB2.gph", replace

  log close
  
  erase  "$outputfolder/NP-Control.gph"
 erase "$outputfolder/NP-Subsidy.gph"
 erase "$outputfolder/NP-CHWonly.gph" 
 erase "$outputfolder/NP-full.gph"
